using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;

namespace TFSAssemblyInfoTask
{
	public class RewriteFileVersions : Task
	{
		private ITaskItem[] assemblyInfoFiles;
		private string assemblyVersionNumber;
		private string assemblyFileVersionNumber;
		private string assemblyInformationalVersionNumber;

		public override bool Execute()
		{
			FileInfo writerInfo = null;
			StreamWriter writer = null;
			foreach (ITaskItem item in AssemblyInfoFiles)
			{
				AssemblyInfoWrapper assemblyInfo = new AssemblyInfoWrapper(item.ItemSpec);
				Log.LogMessage(MessageImportance.Low, "Updating assembly info for {0}", item.ItemSpec);

				assemblyInfo["AssemblyVersion"] = AssemblyVersionNumber;
				assemblyInfo["AssemblyFileVersion"] = AssemblyFileVersionNumber;
				
				try
				{
					writerInfo = this.GetTemporaryFileInfo();
					writer = new StreamWriter(writerInfo.OpenWrite());
					assemblyInfo.Write(writer);
					writer.Close();
					File.Copy(writerInfo.FullName, item.ItemSpec, true);
				}
				finally
				{
					if (writer != null)
						writer.Close();
					if (writerInfo != null)
						writerInfo.Delete();
				}
			}
			return true;
		}

		private FileInfo GetTemporaryFileInfo()
		{
			string tempFileName;
			FileInfo myFileInfo;
			try
			{
				tempFileName = Path.GetTempFileName();
				myFileInfo = new FileInfo(tempFileName);
				myFileInfo.Attributes = FileAttributes.Temporary;
			}
			catch (Exception e)
			{
				Log.LogError("Unable to create temporary file: {0}", e.Message);
				return null;
			}

			return myFileInfo;
		}

		[Required]
		public ITaskItem[] AssemblyInfoFiles
		{
			get { return assemblyInfoFiles; }
			set { assemblyInfoFiles = value; }
		}

		public string AssemblyFileVersionNumber
		{
			get { return assemblyFileVersionNumber; }
			set { assemblyFileVersionNumber = value; }
		}

		/// <summary>
		/// Stub property to maintain compatibility with TFS Guide sample. TODO.
		/// </summary>
		public string AssemblyInformationalVersionNumber
		{
			get { return assemblyInformationalVersionNumber; }
			set { assemblyInformationalVersionNumber = value; }
		}

		public string AssemblyVersionNumber
		{
			get { return assemblyVersionNumber; }
			set { assemblyVersionNumber = value; }
		}
	}
}
